import { Button, Cascader, Col, DatePicker, Divider, Form,Icon,Input, message, Row, Select } from "antd";
import React from "react";
import styles from "./index.less"
import { baseInfoDetail, baseInfoEdit } from "@/services/tenantManagement";
import { businessTypeList, chargingAndDetail } from "@/services/chargingManage";
import BusinessReadonly from "../ChargingManage/businessManage/businessReadonly";
import moment from "moment";

class BaseInfo extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      businessList:[],
      caseOptions:[],
      packageId:""
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    this.getBusinessList()
  }

  getDetail = async (tenantId) => {
    const res = await baseInfoDetail({tenantId})
    const planDetail = res.planDetail ? res.planDetail : {}
    this.setState({packageId:planDetail.packageId})
    this.props.form.setFieldsValue({
      planDetailId:res.planDetailId,
      startTime:res.startTime ? moment(res.startTime) : null,
      endTime:res.endTime ? moment(res.endTime) : null,
      enterpriseId:res.enterpriseId
    })
    this.getCaseOptions(res.enterpriseId)
    this.BusinessReadonly.initModal(res.enterpriseId)
  }

  checkField(rule, value, callback) {
    const reg = /^[0-9a-zA-Z_.@-]{1,}$/g;
    if (rule.field === 'usernameNew') {
      if (value) {
        if (reg.test(value)) {
          if (value.length > 30 || value.length < 6) {
            callback('支持6-30位大小写字母、数字、下划线、小数点、中划线和@符号');
          } else {
            callback();
          }
        } else {
          callback('支持6-30位大小写字母、数字、下划线、小数点、中划线和@符号');
        }
      } else {
        callback('支持6-30位大小写字母、数字、下划线、小数点、中划线和@符号');
      }
    }
  }

  checkFieldForPassword(rule, value, callback) {
    const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
    if (rule.field === 'passwordNew') {
      if (value) {
        if (reg.test(value)) {
          if (value.length > 30 || value.length < 6) {
            callback('只可填入8-20位数字和字母组合');
          } else {
            callback();
          }
        } else {
          callback('只可填入8-20位数字和字母组合');
        }
      } else {
        callback('只可填入8-20位数字和字母组合');
      }
    }
  }

  resetPassword = () => {
    this.props.form.setFieldsValue({passwordNew:"a12345678"})
  }

  addItem = (type,index) => {
    const list = this.state[type]
    list.push('')
    this.setState({[type]:list})
  }

  changeValue = (value,type,index) => {
    const list = this.state[type]
    list[index] = value;
    this.setState({[type]:list})
  }

  checkFormData = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        values.packageId = this.state.packageId
        values.startTime = values.startTime ? moment(values.startTime).format("YYYY-MM-DD") : ''
        values.endTime = values.endTime ? moment(values.endTime).format("YYYY-MM-DD") : ''
        
        if(this.props.tenantId){
          this.doEdit(values)
        }else{
          values.username = values.usernameNew
          if(values.passwordNew){
            values.password = values.passwordNew
          }
          this.props.setFormData({
            step:0,
            nextStep:1,
            value:values
          })
        }
      }
    })
  }

  doEdit = async data => {
    const res = await baseInfoEdit({
      id:this.props.tenantId,
      ...data
    })
    if(res.code != -1){
      message.info(res.message)
    }
    
  }

  getBusinessList = async () => {
    const res = await businessTypeList()
    this.setState({businessList:res.settlement.sort((a, b) => b.id - a.id)})
  }

  getCaseOptions = async id => {
    const res = await chargingAndDetail({id})
    this.setState({caseOptions:res})
  }

  changeBusiness = value => {
    this.props.form.resetFields(["planDetailId"])
    this.getCaseOptions(value)
    this.BusinessReadonly.initModal(value)
  }

  changeDetailId = (value,selectedOptions) => {
    console.log(value,selectedOptions);
    if(selectedOptions && selectedOptions[1]){
      this.setState({packageId:selectedOptions[1].packageId})
    }
  }

  disabledendTime = endValue => {
    const startValue = this.props.form.getFieldValue("startTime")
    
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };

  render(){
    const { form:{getFieldDecorator,getFieldValue,resetFields},current,tenantId } = this.props
    const { businessList,caseOptions } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    return (
      <div className={styles.add} style={{display:current == 0 ? "block" : "none"}}>
        <Form {...formItemLayout}>
          <h3>基础信息</h3>
          <Row>
            <Col span={12}>
              <Form.Item label="选择绑定企业">
                {getFieldDecorator("enterpriseId",{rules:[{required:true,message:"请选择"}]})(
                  <Select showSearch optionFilterProp="children" onChange={this.changeBusiness}>
                    {businessList.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="计费方案明细">
                {getFieldDecorator("planDetailId",{rules:[{required:true,message:"请选择"}]})(
                  <Cascader options={caseOptions} fieldNames={{ label: 'name', value: 'id', children: 'children' }} onChange={this.changeDetailId} />
                )}
              </Form.Item>
              <Form.Item label="账户有效开始日">
                {getFieldDecorator("startTime",{rules:[{required:true,message:"请选择"}]})(
                  <DatePicker onChange={() => resetFields(["endTime"])} />
                )}
              </Form.Item>
              <Form.Item label="账户有效截至日">
                {getFieldDecorator("endTime",{rules:[{required:true,message:"请选择"}]})(
                  <DatePicker disabled={!getFieldValue("startTime") } disabledDate={this.disabledendTime} />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              {
                tenantId ? '' : (
                  <Form.Item label={'账号'}>
                    {getFieldDecorator('usernameNew', {
                      rules: [{ required: true, message: '账号必填' }, { validator: this.checkField },]
                    })(<Input placeholder={'请填写账号'} maxLength={60} style={{ width: '200px' }} disabled={tenantId ? true : false} autoComplete="new-user" />)}
                  </Form.Item>
                )
              }
              
              {tenantId ? '' : (
                <Form.Item label={'密码'}>
                  {getFieldDecorator('passwordNew', {
                    rules: [{ required: true, message: '密码必填' }, { validator: this.checkFieldForPassword, }]
                  })(<Input.Password placeholder={'请填写密码'} maxLength={60} style={{ width: '200px' }} autoComplete="new-password" />)}
                  <Button icon="sync" type="link" style={{marginLeft:10}} onClick={this.resetPassword}>默认密码</Button>
                </Form.Item>
              )}
            </Col>
          </Row>
          
          <Divider />
          
          <BusinessReadonly onRef={ref => this.BusinessReadonly = ref} />
        </Form>
      </div>
    )
  }
}

export default Form.create()(BaseInfo)